package com.aleaho.cftrack.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.model.Point;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

/**
 * 常用的公共方法
 * <p>
 * Created by Administrator on 2017/10/21.
 */

public class CommonUtil {

    private static DecimalFormat df = new DecimalFormat("######0.00");

    public static final double DISTANCE = 0.0001;


    /**
     * 根据程序上下文信息，获得程序的名称。
     *
     * @param context 程序的上下文信息。
     * @return 程序的名称。
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }


    /**
     * 获取当前时间的字符串形式。
     *
     * @return 当前时间的字符串，格式为 "yyyy-MM-dd HH:mm:ss"
     */
    public static String getCurrentTimeString() {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(dt);
    }


    /**
     * 将当前日历时间转换成字符串形式
     * @param calendar
     * @return
     */
    public static String canlenderToTimeString(Calendar calendar) {
        Date dt = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(dt);
    }


    /**
     * 获取单钱的时间戳(单位：秒)
     *
     * @return
     */
    public static long getCurrentTime() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 校验double数值是否为0。
     *
     * @param value 待校验的数值。
     * @return 校验结果。
     * <p>
     * <pre>true:等于0。</pre>
     * <pre>false:不等于0。</pre>
     * </p>
     */
    public static boolean isEqualToZero(double value) {
        return Math.abs(value - 0.0) < 0.01 ? true : false;
    }


    /**
     * 经纬度是否为（0,0）点
     *
     * @param latitude  维度
     * @param longitude 经度
     * @return
     */
    public static boolean isZeroPoint(double latitude, double longitude) {
        return isEqualToZero(latitude) && isEqualToZero(longitude);
    }


    public static long toTimeStamp(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss",
                Locale.CHINA);

        Date date;

        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            Log.e(Constants.TAG, e.getLocalizedMessage());
            return 0;
        }

        return date.getTime() / 1000;
    }


    /**
     * 获取时分秒
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String getHMS(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 获取年月日 时分秒
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String formatTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    public static String formatSecond(int second) {
        String format = "%1$,02d:%2$,02d:%3$,02d";
        Integer hours = second / (60 * 60);
        Integer minutes = second / 60 - hours * 60;
        Integer seconds = second - minutes * 60 - hours * 60 * 60;
        Object[] array = new Object[]{hours, minutes, seconds};
        return String.format(format, array);
    }

    public static final String formatDouble(double doubleValue) {
        return df.format(doubleValue);
    }

    /**
     * 计算x方向每次移动的距离
     */
    public static double getXMoveDistance(double slope) {
        if (slope == Double.MAX_VALUE) {
            return DISTANCE;
        }
        return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope));
    }

    /**
     * 根据点和斜率算取截距
     */
    public static double getInterception(double slope, LatLng point) {
        return point.latitude - slope * point.longitude;
    }

    /**
     * 算斜率
     */
    public static double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        return (toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude);
    }

    /**
     * 根据两点算取图标转的角度
     */
    public static double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        return 180 * (radio / Math.PI) + deltAngle - 90;
    }

    //    /**
    //     * 保存当前定位点
    //     */
    //    public static void saveCurrentLocation(CFTrackApplication trackApp) {
    //        SharedPreferences.Editor editor = trackApp.trackConf.edit();
    //        StringBuffer locationInfo = new StringBuffer();
    //        locationInfo.append(CurrentLocation.locTime);
    //        locationInfo.append(";");
    //        locationInfo.append(CurrentLocation.latitude);
    //        locationInfo.append(";");
    //        locationInfo.append(CurrentLocation.longitude);
    //        editor.putString(Constants.LAST_LOCATION, locationInfo.toString());
    //        editor.apply();
    //    }

    /**
     * 获取设备IMEI码
     *
     * @param context
     * @return
     */
    public static String getImei(Context context) {
        String imei;
        try {
            imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        } catch (Exception e) {
            imei = "myTrace";
        }
        return imei;
    }


    /**
     * 将坐标转换成为地址
     *
     * @param point
     * @return
     */
    public static String lngLatToAddress(Point point) {
        //http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=32.473319053749,117.17679115698&output=json&pois=1&ak=XxMXSseLUmRutxWwqLVcUyquXSrFIG74

        String lngLat = "32.473319053749,117.17679115698";
        String url = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + lngLat + "&output=json&pois=1&ak=XxMXSseLUmRutxWwqLVcUyquXSrFIG74";


        return "";
    }


    /**
     * 查询指定服务是否正在运行
     *
     * @param mContext
     * @param serviceName 服务名称
     * @return boolean
     */
    public static boolean isServiceRunning(Context mContext, String serviceName) {
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceList = myAM.getRunningServices(80);
        for (ActivityManager.RunningServiceInfo runningService : runningServiceList) {
            String mName = runningService.service.getClassName().toString();
            if (mName.equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

}
